var webwx = require('./../webwx'),
    utils = require('./utils'),
    constant = require('./../constant'),
    tulingRot = require('./tulingRot');

var matchGroupContent = utils.matchGroupContent;

var webwxsendmsg = webwx.webwxsendmsg,
    webwxbatchgetcontact = webwx.webwxbatchgetcontact,
    sendWxMsgByTuling = tulingRot.sendWxMsgByTuling;

/**
 * 自动回复
 * @param wxSession
 * @returns {function(*)}
 */
var autoreplyRes = (wxSession) => {
    return msgBody => {
        if (!msgBody) {
            console.error("消息体为null");
            return;
        }
        switch (msgBody.MsgType) {
            case constant.MSGTYPE_TEXT:
                autoReplyTextContent(msgBody, wxSession);
                break;
            case constant.MSGTYPE_RECALL:
                console.log('有人撤回消息了。');
                console.log(msgBody);
                break;
            default :
                console.log('其他信息暂时不处理。' + msgBody.MsgType);
        }
    }
}

/**
 * 处理文本类型的信息
 * @param msgBody
 * @param wxSession
 */
function autoReplyTextContent(msgBody, wxSession) {
    var content = msgBody.Content;
    var fromUserName = msgBody.FromUserName;
    // 判断是否为群消息,并且@我的
    if (fromUserName.startsWith('@@')) {
        // 查看缓存中是会否存在群的信息
        var contactP;
        if (!(fromUserName in wxSession.groupContact)) {
            console.log('更新群缓存')
            var contactP = webwxbatchgetcontact(fromUserName, wxSession);
        }
        console.log(typeof contactP);
        if (contactP && typeof contactP == "object") {
            contactP.then(function (wxSession) {
                console.log('先更新缓存，在发送信息');
                groupReply(msgBody, wxSession);
            })
        } else {
            console.log('没有缓存更新，直接发送信息');
            groupReply(msgBody, wxSession);
        }
    } else { // 这不是群信息
        sendWxMsgByTuling(content, fromUserName, wxSession);
    }
}

/**
 * 群消息（文本类型）处理
 * @param msgBody
 * @param wxSession
 */
function groupReply(msgBody, wxSession) {
    var content = msgBody.Content;
    var fromUserName = msgBody.FromUserName;
    // 判断是否为@我
    if (content.includes("@" + wxSession.nickname)) {
        console.log('有人在群里@我。');
        var contentObj = matchGroupContent(content);
        var fromMemberId = contentObj.fromMemberId;
        var realContent = contentObj.message;
        // 获取谁@了我
        var groupMembers = wxSession.groupContact[fromUserName];
        var result = groupMembers.memberList.filter(o => (o.UserName == fromMemberId));
        var fromMember;
        if (result.length > 0) {
            fromMember = result[0];
        }
        console.log(fromMember);
        sendWxMsgByTuling(realContent, fromUserName, wxSession, (data) => {
            webwxsendmsg("@" + fromMember.NickName + " " + (data != undefined ? data : ''), fromUserName, wxSession);
        });
    }
    else {
        console.log('不是@我的信息，不用管。' + msgBody.MsgType);
        return;
    }
}

module.exports.autoreplyRes = autoreplyRes;